(function(){
    _$(document).ready(function(){
        function App(){};
        App.prototype.ajaxFn=function(){
            //判断是否阅读然后隐藏cover
            if(session){
                _$.post('/getBookshelfType',{bid:bid},function(data){
                    if(data['code']==1){
                        console.log("已在书架");
                        if(data.info==null){

                        }else{
                            if(data.info.chapterName=="尚未阅读"){

                            }else{
                                _$("#readCover").hide();
                            }
                        }
                    }else{
                        console.log(data['msg']);
                        pdhc();
                    }
                });
            }
            //获取书本信息
            _$.post('/getbookInfo',{bid:bid},function(data) {
                console.log(data);
                if(data['code']==1){
                    var info=data.info.bookInfo;
                    //设置书本封面
                    _$("#coverFigure").attr('src',info['imgurl']);
                    //设置书本名称
                    _$("#coverTitle").html(info['bName']);
                    //设置作者
                    _$("#coverAuthor").html(info['bAuth']+" 著");
                    //设置类型
                    _$("#cat").html(info['cat']);
                    //设置书本创建时间
                    _$("#startTime").html(getTimes(info['startTime'],'YY-MM-DD'));
                    //字数大于10000就转换
                    if(info['cnt']>10000){
                        info['cnt']=info['cnt']/10000;
                        _$("#cnt").html(info['cnt'].toFixed(2)+"万");
                    }else{
                        _$("#cnt").html(info['cnt']);
                    }
                    //设置头信息
                    _$("title").html(info['bName']+"_"+info['bAuth']+"著_异世大陆小说_"+info['bName']+"txt下载_"+info['bName']+"无弹窗_起点中文网");
                    _$("#meta1").html(info['bName']+"官方首发,"+info['bName']+"小说,"+info['bName']+"最新章节,"+info['bName']+"txt下载,"+info['bName']+"无弹窗,超级浮空城吧,"+info['bName']+"离线完本");
                    _$("#meta2").html(info['bName']+","+info['bName']+"小说阅读,异世大陆小说"+info['bName']+"由作家"+info['bAuth']+"创作,起点中文网提供"+info['bName']+"首发最新章节及txt下载,"+info['bName']+"最新更新章节,更多精彩尽在起点中文网。");
                    //要缓存作者id
                    _$("#aid").val(info['cid']);
                    //要缓存作者名字
                    _$("#aName").val(info['bAuth']);
                    //要缓存书本名字
                    _$("#bName").val(info['bName']);
                    //要缓存书本封面
                    _$("#imgurl").val(info['imgurl']);
                }
            });
            //获取所有章节
            _$.post('/getChapter',{bid:bid,seq:true},function(data){
                if(data['code']==1){
                    if(data['info'].length>0){
                        var info=data['info'];
                        var html="";
                        for(var val in info){
                            html+='<li class="chapter-li" data-chapter-id="'+info[val]['chapters']+'" data-chapter-name="'+info[val]['title']+'">';
                            html+='<a class="chapter-li-a">';
                            if(chapter==info[val]['chapters']){
                                html+='<span class="chapter-index red">'+info[val]['title']+'</span>';
                            }else{
                                html+='<span class="chapter-index ">'+info[val]['title']+'</span>';
                            }
                            html+='</a>';
                            html+='</li>';
                        }
                        //生成目录
                        _$("#chapterCatalog").html(html);
                        //目录点击事件
                        hc();
                    }else{
                        //没有章节时
                        _$("#chapterCatalog").html('<div class="null-x"><div class="null">暂无章节</div></div>');
                    }
                    //章节的长度
                    _$("#chapterall").html(data['info'].length);
                }
            });
            //章节显示
            _$.ajax({
                type:'post',
                url:'/getChapterObj',
                data:{bid:bid},
                async:false,
                success:function(data){
                    console.log(data);
                    if(data['code']==1){
                        var itemIndex = 0;
                        var chapter1=chapter-1;//下拉上一章
                        var chapter2=chapter-1;//上拉下一章
                        // dropload
                        var dropload = $('.khfxWarp').dropload({
                            scrollArea: window,
                            domUp : {
                                domClass   : 'dropload-up',
                                // 下拉过程显示内容
                                domRefresh : '<div class="dropload-refresh">↓下拉加载</div>',
                                // 下拉到一定程度显示提示内容
                                domUpdate  : '<div class="dropload-update">暂无数据</div>',
                                // 释放后显示内容
                                domLoad    : '<div class="dropload-load"><span class="loading"></span>加载中...</div>'
                            },
                            domDown: {
                                domClass: 'dropload-down',
                                domRefresh: '<div class="dropload-refresh">↑上拉加载</div>',
                                domLoad    : '<div class="dropload-load"><span class="loading"></span>加载中...</div>',
                                domNoData: '<div class="dropload-noData">已无数据</div>'
                            },
                            // 1 . 下拉 回调函数
                            loadUpFn : function(me){
                                if(chapter1<1){
                                    //没有章节时停用上下拉插件
                                    me.lock();
                                    me.noData();
                                    me.resetload();
                                }else{
                                    //设置要缓存的章节
                                    _$("#cid").val(chapter1);
                                    $.ajax({
                                        type: 'post',
                                        // 每次获取最新的数据即可
                                        url: '/getChapterText',
                                        data:{chapter:chapter1,bid:bid},
                                        async:false,
                                        success: function(json) {
                                            if(json.code==1){
                                                var info = json.info.info;
                                                var txt = json.info.result;
                                                //章节标题
                                                _$("#chapterTitle").html(info['title']);
                                                //设置要缓存章节标题
                                                _$("#cName").val(info['title']);
                                                //拼装html
                                                var result = '';
                                                result += "<div class='read-article' data-title='"+info['title']+"' data-chapter-id='"+info['chapters']+"'><h3>" + info['title'] + "</h3><div class='mainContenr'>"
                                                result += txt;
                                                result += "</div></div>";

                                                // 延迟1秒加载
                                                setTimeout(function () {
                                                    // 插入加载使用 html() 重置 DOM
                                                    $('.khfxPane').eq(itemIndex).prepend(result);
                                                    if(session){
                                                        _$.post('/setBookChapter',{
                                                            bid:bid,
                                                            cid:_$("#cid").val(),
                                                            cName:_$("#cName").val()
                                                        },function(data){
                                                            //console.log(data);
                                                            addhc();
                                                        });
                                                    }else{
                                                        addhc();
                                                    }
                                                    _$(".chapter-li-a span").removeClass('red');
                                                    _$(".chapter-li").each(function(){
                                                        if(_$(this).attr('data-chapter-id')==_$("#cid").val()){
                                                            _$(this).find('.chapter-li-a span').addClass('red');
                                                        }
                                                    });
                                                    //每次加载判断是否夜间模式
                                                    if(_$("#nightBtn").find('i').hasClass('icon-sun')){
                                                        _$(".read-article").addClass('nightColor');
                                                    }else{
                                                        _$(".read-article").removeClass('nightColor');
                                                    }
                                                    //每次加载都拿设置好的字体大小
                                                    _$('.mainContenr').css('font-size',_$("#readFontSize").val()+"px");
                                                    chapter1--;
                                                    //滚动到哪章，标题变哪章
                                                    var _ra=_$(".read-article");
                                                    $(window).on('scroll', function() {
                                                        for(var i = 0; i < _ra.length; i++)
                                                        {
                                                            var $ra = _ra.eq(i), st = $(window).scrollTop();
                                                            var top = $ra.offset().top;
                                                            if (st >= top && st <= $ra.height() + top) //  top >= st >= top + height
                                                            {
                                                                _$("#chapterTitle").html($ra.attr('data-title'));
                                                                _$("#cid").val($ra.attr('data-chapter-id'));
                                                                _$("#cName").val($ra.attr('data-title'));
                                                                if(session){
                                                                    _$.post('/setBookChapter',{
                                                                        bid:bid,
                                                                        cid:_$("#cid").val(),
                                                                        cName:_$("#cName").val()
                                                                    },function(data){
                                                                        //console.log(data);
                                                                        addhc();
                                                                    })
                                                                }else{
                                                                    addhc();
                                                                }
                                                                _$(".chapter-li-a span").removeClass('red');
                                                                _$(".chapter-li").each(function(){
                                                                    if(_$(this).attr('data-chapter-id')==_$("#cid").val()){
                                                                        _$(this).find('.chapter-li-a span').addClass('red');
                                                                    }
                                                                });
                                                                break;
                                                            }
                                                        }

                                                    });
                                                    // 每次数据加载完，必须重置
                                                    me.resetload();
                                                }, 1000);
                                            }else{
                                                    tip("暂无本书章节");
                                                    _$("#chapterTitle").html("暂无本书章节");
                                                    me.lock();
                                                    me.noData();
                                                    me.resetload();
                                                }
                                            },
                                        // 加载出错
                                        error: function(xhr, type){
                                            alert('Ajax error!');
                                            // 即使加载出错，也得重置
                                            me.resetload();
                                        }
                                    });
                                }

                            },
                            //上拉
                            loadDownFn: function (me) {
                                chapter2++;
                                if(chapter2>data['info'].length){
                                    me.lock();
                                    me.noData();
                                    me.resetload();
                                }else{
                                    //设置要缓存的章节
                                    _$("#cid").val(chapter2);
                                    _$.ajax({
                                        type: 'post',
                                        // 每次获取最新的数据即可
                                        url: '/getChapterText',
                                        data:{chapter:chapter2,bid:bid},
                                        async:false,
                                        success: function(json){
                                            if(json.code==1){
                                                var info=json.info.info;
                                                var txt=json.info.result;
                                                //章节标题
                                                _$("#chapterTitle").html(info['title']);
                                                //设置要缓存章节标题
                                                _$("#cName").val(info['title']);
                                                //拼装html
                                                var result = '';
                                                result += "<div class='read-article' data-title='"+info['title']+"' data-chapter-id='"+info['chapters']+"'><h3>" + info['title'] + "</h3><div class='mainContenr'>"
                                                result+=txt;
                                                result+="</div></div>";

                                                //延迟1秒加载
                                                setTimeout(function(){
                                                    // 插入加载使用 html() 重置 DOM
                                                    $('.khfxPane').eq(itemIndex).append(result);
                                                    if(session){
                                                        _$.post('/setBookChapter',{
                                                            bid:bid,
                                                            cid:_$("#cid").val(),
                                                            cName:_$("#cName").val()
                                                        },function(data){
                                                            //console.log(data);
                                                            addhc();
                                                        })
                                                    }else{
                                                        addhc();
                                                    }
                                                    _$(".chapter-li-a span").removeClass('red');
                                                    _$(".chapter-li").each(function(){
                                                        if(_$(this).attr('data-chapter-id')==_$("#cid").val()){
                                                            _$(this).find('.chapter-li-a span').addClass('red');
                                                        }
                                                    });
                                                    //每次加载判断是否夜间模式
                                                    if(_$("#nightBtn").find('i').hasClass('icon-sun')){
                                                        _$(".read-article").addClass('nightColor');
                                                    }else{
                                                        _$(".read-article").removeClass('nightColor');
                                                    }
                                                    _$('.mainContenr').css('font-size',_$("#readFontSize").val()+"px");
                                                    var _ra=_$(".read-article");
                                                    //滚动到哪章，标题变哪章
                                                    $(window).on('scroll', function() {
                                                        for(var i = 0; i < _ra.length; i++)
                                                        {
                                                            var $ra = _ra.eq(i), st = $(window).scrollTop();
                                                            var top = $ra.offset().top;
                                                            if (st >= top && st <= $ra.height() + top) //  top >= st >= top + height
                                                            {
                                                                _$("#chapterTitle").html($ra.attr('data-title'));
                                                                _$("#cid").val($ra.attr('data-chapter-id'));
                                                                _$("#cName").val($ra.attr('data-title'));
                                                                if(session){
                                                                    _$.post('/setBookChapter',{
                                                                        bid:bid,
                                                                        cid:_$("#cid").val(),
                                                                        cName:_$("#cName").val()
                                                                    },function(data){
                                                                        //console.log(data);
                                                                        addhc();
                                                                    })
                                                                }else{
                                                                    addhc();
                                                                }
                                                                _$(".chapter-li-a span").removeClass('red');
                                                                _$(".chapter-li").each(function(){
                                                                    if(_$(this).attr('data-chapter-id')==_$("#cid").val()){
                                                                        _$(this).find('.chapter-li-a span').addClass('red');
                                                                    }
                                                                });
                                                                break;
                                                            }
                                                        }

                                                    });
                                                    // 每次数据加载完，必须重置
                                                    me.resetload();
                                                },1000);
                                            }else{
                                                tip("暂无本书章节");
                                                _$("#chapterTitle").html("暂无本书章节");
                                                me.lock();
                                                me.noData();
                                                me.resetload();
                                            }
                                        },
                                        // 加载出错
                                        error: function(xhr, type){
                                            alert('Ajax error!');
                                            // 即使加载出错，也得重置
                                            me.resetload();
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
        };
        App.prototype.eventFn=function(){
            //拼装目录HTML
            function pzhtml(info){
                var html="";
                for(var val in info){
                    html+='<li class="chapter-li" data-chapter-id="'+info[val]['chapters']+'" data-chapter-name="'+info[val]['title']+'">';
                    html+='<a class="chapter-li-a">';
                    if(chapter==info[val]['chapters']){
                        html+='<span class="chapter-index red">'+info[val]['title']+'</span>';
                    }else{
                        html+='<span class="chapter-index ">'+info[val]['title']+'</span>';
                    }
                    html+='</a>';
                    html+='</li>';
                }
                return html;
            }
            //点击目录倒序
            _$("#reverse").click(function(){
                var key=_$(this).attr('data-key');
                //倒序
                if(key=='1'){
                    //清空目录HTML
                    _$("#chapterCatalog").html("");
                    //获取目录
                    _$.post('/getChapter',{bid:bid,seq:false},function(data){
                        if(data['code']==1){
                            if(data['info'].length>0){
                                var info=data['info'];
                                _$("#chapterCatalog").html(pzhtml(info));
                                hc();
                            }else{
                                _$("#chapterCatalog").html('<div class="null-x"><div class="null">暂无章节</div></div>');
                            }
                            _$("#chapterall").html(data['info'].length);
                        }
                    });
                    _$(this).html('顺序').attr('data-key','0');
                 //正序
                }else if(key=='0'){
                    _$("#chapterCatalog").html("");
                    _$.post('/getChapter',{bid:bid,seq:true},function(data){
                        if(data['code']==1){
                            if(data['info'].length>0){
                                var info=data['info'];
                                _$("#chapterCatalog").html(pzhtml(info));
                                hc();
                            }else{
                                _$("#chapterCatalog").html('<div class="null-x"><div class="null">暂无章节</div></div>');
                            }
                            _$("#chapterall").html(data['info'].length);
                        }
                    });
                    _$(this).html('倒序').attr('data-key','1');
                }
            });
            //背景变换
            _$(".read-set-cell").click(function(e){
                e.stopPropagation();
                _$(this).addClass('active').siblings('.read-set-cell').removeClass('active');
                _$('.bgimg').attr('class',"bgimg "+_$(this).attr('data-bg'));
                _$('.page-read-top').attr('class',"page-read-top "+_$(this).attr('data-bg'));
                _$('#nightBtn').find('span').html("夜间");
                _$('#nightBtn').find('i').removeClass('icon-sun');
                _$('#nightBtn').attr('data-key',"1");
                _$('.page-read-top,.bgimg,.read-article').removeClass('nightColor');
            });
            //隐藏弹出
            _$(".khfxPane").click(function(){
                _$("#pageReadOpt").fadeIn();
            });
            //夜间模式
            _$('#nightBtn').click(function(){
                var key=_$(this).attr('data-key');
                if(key==1){
                    _$(this).find('span').html("日间");
                    _$(this).find('i').addClass('icon-sun');
                    _$(this).attr('data-key',"0");
                    _$('.page-read-top,.bgimg,.read-article').addClass('nightColor');
                }else if(key=="0"){
                    _$(this).find('span').html("夜间");
                    _$(this).find('i').removeClass('icon-sun');
                    _$(this).attr('data-key',"1");
                    _$('.page-read-top,.bgimg,.read-article').removeClass('nightColor');
                }
            });
            _$("#openChapter").click(function(){
                _$("#asideChapter").fadeIn();
            });
            _$("#asideOverlay").click(function(){
                _$("#asideChapter").fadeOut();
            });
            _$("#btnTab span").click(function(){
                var index=_$(this).index();
                _$(this).addClass('active').siblings('span').removeClass('active');
                _$("#tabContent .list").eq(index).addClass('active').siblings('.list').removeClass('active');
            });
            function clickShow(dom1,dom2,dom3,dom4){
                _$(dom1).click(function(){
                    var key=_$(this).attr('data-key');
                    var that=_$(this);
                    _$(dom3).attr('data-key','1');
                    _$(dom4).fadeOut();
                    if(key=='1'){
                        _$(dom2).fadeIn();
                        that.attr('data-key','0');
                    }else if(key=='0'){
                        _$(dom2).fadeOut();
                        that.attr('data-key','1');
                    }
                });
            }
            //字体大小
            _$("#readFontSize").keyup(function(){
                console.log(_$(this).val());
                _$('.mainContenr').css('font-size',_$(this).val()+"px");
            });
            //字体大小
            _$("#readFontSize").blur(function () {
                if(!isNaN(_$(this).val())){
                    if(_$("#readFontSize").val()<=10){
                        _$("#readFontSize").val(16);
                        _$('.mainContenr').css('font-size',"16px");
                        tip("不能小于10");
                    }
                }else{
                    tip("输入的不是数字");
                    _$("#readFontSize").val(16);
                }
            });
            //字体大小+
            _$("#ajia").click(function(){
                var val=_$("#readFontSize").val();
                val++;
                _$("#readFontSize").val(val);
                _$('.mainContenr').css('font-size',val+"px");
            });
            //字体大小-
            _$("#ajian").click(function(){
                var val=_$("#readFontSize").val();
                if(val<=10){

                }else{
                    val-=1;
                }
                _$("#readFontSize").val(val);
                _$('.mainContenr').css('font-size',val+"px");
            });
            clickShow("#iconGd","#readMoreX","#openSet","#readOptSet");
            clickShow("#openSet","#readOptSet","#iconGd","#readMoreX");
            _$('.read-opt-a,.read-set-font a,.read-font-size').click(function(e){
                e.stopPropagation();
            });
            _$(".read-opt-content").click(function(){
                _$("#readMoreX,#readOptSet").fadeOut();
                _$("#iconGd,#openSet").attr('data-key','1');
                _$("#pageReadOpt").fadeOut();
            });
            _$("#readCover").click(function(){
                _$(this).fadeOut();
            });
        };
        function hc(){
            _$("#chapterCatalog .chapter-li").click(function(){
                function dlhc(taht){
                    var localRead=localStorage.getItem('OLD_READ');
                    var readobj={
                        bid:bid,
                        bName:_$("#bName").val(),
                        aid:_$("#aid").val(),
                        aName:_$("#aName").val(),
                        cid:taht.attr('data-chapter-id'),
                        cName:taht.attr('data-chapter-name'),
                        time:new Date().getTime(),
                        imgurl:_$("#imgurl").val()
                    };
                    if(localRead==""||localRead==null||localRead==undefined){
                        localStorage.setItem('OLD_READ',JSON.stringify([readobj]));
                    }else{
                        var bidkey=true;
                        var localReadObj=JSON.parse(localRead);
                        for(var val in localReadObj){
                            if(localReadObj[val]['bid']==bid){
                                localReadObj[val]['bName']=_$("#bName").val();
                                localReadObj[val]['aid']=_$("#aid").val();
                                localReadObj[val]['aName']=_$("#aName").val();
                                localReadObj[val]['cid']=taht.attr('data-chapter-id');
                                localReadObj[val]['cName']=taht.attr('data-chapter-name');
                                localReadObj[val]['time']=new Date().getTime();
                                localReadObj[val]['imgurl']=_$("#imgurl").val();
                                bidkey=false;
                                break;
                            }
                        }
                        if(bidkey){
                            localReadObj.push(readobj);
                        }
                        localStorage.setItem('OLD_READ',JSON.stringify(localReadObj));
                        location.href="/look/"+bid+"?chapter="+taht.attr('data-chapter-id');
                    }
                }
                var taht=_$(this);
                if(session){
                    _$.post('/setBookChapter',{
                        bid:bid,
                        cid:taht.attr('data-chapter-id'),
                        cName:taht.attr('data-chapter-name')
                    },function(data){
                        console.log(data);
                        dlhc(taht);
                    })
                }else{
                    dlhc(taht);
                }
            });
            pdhc();
        }
        function pdhc(){
            var localRead=localStorage.getItem('OLD_READ');
            if(localRead==""||localRead==null||localRead==undefined){

            }else{
                var bidkey=true;
                var localReadObj=JSON.parse(localRead);
                for(var val in localReadObj){
                    if(localReadObj[val]['bid']==bid){
                        bidkey=false;
                        break;
                    }
                }
                if(bidkey){

                }else{
                    _$("#readCover").hide();
                }
            }
        }
        function addhc(){
            var localRead=localStorage.getItem('OLD_READ');
            var readobj={
                bid:bid,
                bName:_$("#bName").val(),
                aid:_$("#aid").val(),
                aName:_$("#aName").val(),
                cid:_$("#cid").val(),
                cName:_$("#cName").val(),
                time:new Date().getTime(),
                imgurl:_$("#imgurl").val()
            };
            if(localRead==""||localRead==null||localRead==undefined){
                localStorage.setItem('OLD_READ',JSON.stringify([readobj]));
            }else{
                var bidkey=true;
                var localReadObj=JSON.parse(localRead);
                for(var val in localReadObj){
                    if(localReadObj[val]['bid']==bid){
                        localReadObj[val]['bName']=_$("#bName").val();
                        localReadObj[val]['aid']=_$("#aid").val();
                        localReadObj[val]['aName']=_$("#aName").val();
                        localReadObj[val]['cid']=_$("#cid").val();
                        localReadObj[val]['cName']=_$("#cName").val();
                        localReadObj[val]['time']=new Date().getTime();
                        localReadObj[val]['imgurl']=_$("#imgurl").val();
                        bidkey=false;
                        break;
                    }
                }
                if(bidkey){
                    localReadObj.push(readobj);
                }else{
                    _$("#readCover").hide();
                }
                localStorage.setItem('OLD_READ',JSON.stringify(localReadObj));
            }
        }
        App.prototype.init=function(){
            //事件调用
            this.eventFn();
            this.ajaxFn();

        };
        //程序初始化
        new App().init();
    })
})();